package com.example.month11.vp_tab;

import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.month11.vp_tab.fragment.TabFragment;
import com.example.month11.vp_tab.view.TabView;
import com.example.recyclerview01.R;
import com.example.utils.L;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 微信主界面实现效果(ViewPager+Fragment)。Tab切换时，底部tab有动画效果。
 * 旋转屏幕，底部tab不记录。
 */
public class WeChatHomeActivityWithTab extends AppCompatActivity {
    private ViewPager mVpMain;
    private List<String> mTitles = new ArrayList<>(Arrays.asList("微信", "通讯录", "发现", "我的"));

    private TabView mTabWechat;
    private TabView mTabFriend;
    private TabView mTabFind;
    private TabView mTabMine;
    private List<TabView> mTabs = new ArrayList<>();

    // 合理管理Fragment 的方式。
    private SparseArray<Fragment> mFragments = new SparseArray<>();
    public static final String BUNDLE_KEY_POS = "bundle_key_pos";
    private int mCurrentTabPos = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_we_chat_home_tab);
        setTitle("微信主界面UI");
        if (savedInstanceState!=null) {
            // 系统重建activity，使用之前存储的关键信息。onSaveInstanceState
            mCurrentTabPos = savedInstanceState.getInt(BUNDLE_KEY_POS, 0);
        }

        initViewPagerAdapter();
        initButtons();
        initEvents();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // 结局屏幕旋转，底部tab选中的bug。保存变量
        outState.putInt(BUNDLE_KEY_POS, mVpMain.getCurrentItem());
        super.onSaveInstanceState(outState);
    }

    private void initEvents() {
        for (int i = 0; i < mTabs.size(); i++) {
            TabView tabView = mTabs.get(i);
            int finalI = i;
            tabView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 切换时，不需要动画效果。
                    mVpMain.setCurrentItem(finalI, false);
                    setTabCurrentTab(finalI);
                }
            });
        }
    }


    private void initButtons() {
        mTabWechat = findViewById(R.id.tab_wechat);
        mTabFriend = findViewById(R.id.tab_friend);
        mTabFind = findViewById(R.id.tab_find);
        mTabMine = findViewById(R.id.tab_mine);

        mTabWechat.setIconAndText(R.drawable.wechat, R.drawable.wechat_select, "微信");
        mTabFriend.setIconAndText(R.drawable.friend, R.drawable.friend_select, "通讯录");
        mTabFind.setIconAndText(R.drawable.find, R.drawable.find_select, "发现");
        mTabMine.setIconAndText(R.drawable.mine, R.drawable.mine_select, "我的");

        mTabs.add(mTabWechat);
        mTabs.add(mTabFriend);
        mTabs.add(mTabFind);
        mTabs.add(mTabMine);

        setTabCurrentTab(mCurrentTabPos); // 默认选中第一个item
    }

    // 设置显示的tab。
    private void setTabCurrentTab(int pos) {
        for (int i = 0; i < mTabs.size(); i++) {
            TabView tabView = mTabs.get(i);
            if (i == pos) {
                tabView.setProgress(1);
            } else {
                tabView.setProgress(0);
            }
        }
    }

    private void initViewPagerAdapter() {
        mVpMain = findViewById(R.id.vp_main);
        mVpMain.setOffscreenPageLimit(mTitles.size()); // 设置缓存数量。（2n+1）
        mVpMain.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                // 相当于CreateFragment
                TabFragment tabFragment = TabFragment.newInstance(mTitles.get(position));
                return tabFragment;
            }

            @Override
            public int getCount() {
                return mTitles.size();
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                TabFragment tabFragment = (TabFragment) super.instantiateItem(container, position);
                mFragments.put(position, tabFragment); // 添加到集合中
                return tabFragment;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                // 从集合中移除。保证界面中有几个Fragment，mFragments就有几个。而且是一一对应的。
                mFragments.remove(position);
                super.destroyItem(container, position, object);
            }
        });

        // 监听页面滚动
        mVpMain.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                L.d("onPageScrolled: pos" + position + ",positionOffset" + positionOffset + ",OffsetPixels" + positionOffsetPixels);
                // 从左到右滑动0->1: left pos, right pos+1; positionOffset:0~1
                // leftProgress:1~0（1-positionOffset）; rightProgress:0~1（positionOffset）.
                // 从右到左滑动1->0: left pos, right pos+1; positionOffset:1~0
                // leftProgress:0~1（1-positionOffset）; rightProgress:1~0（positionOffset）.

                // 获取Tab，给Tab设置progress。
                if (positionOffset > 0) { // 处理异常。
                    TabView left = mTabs.get(position);
                    TabView right = mTabs.get(position + 1);
                    left.setProgress((1 - positionOffset));
                    right.setProgress(positionOffset);
                }
            }

            @Override
            public void onPageSelected(int position) {
                L.d("onPageSelected: " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

}
